<template>
	<view class="order-detail" v-if="detail" :class="type==2||type==3?'order-pt1':''">
		<view class="order-section pd1 mt-none">
			<view class="order-number">
				<view class="number-left">
					<text>{{orderCode}}</text>
					<image @tap="copy(orderCode)" src="~@/packageC/static/img/copy.png"></image>
				</view>
				<view class="status" v-html="getOrderStatus(detail.orderInfo.orderStatus)"></view>
			</view>
			<view class="tui-goods-item goods-item" v-for="item in afterList">
				<view class="tui-goods-img">
					<image :src="imgSrc + item.imgUrl" />
				</view>
				<view class="tui-goods-info">
					<view class="tui-goods-title">{{item.goodsName}} {{item.goodsMatcode}}</view>
					<view class="tui-goods-sub">产品码：
						<text v-if="item.uniqueCodeList&&item.uniqueCodeList.length==1">{{item.uniqueCodeList[0].goodsCode}}</text>
						<text class="code-text" v-if="item.uniqueCodeList&&item.uniqueCodeList.length>1" @tap="viewCodesModal($event,index,item.uniqueCodeList)"
						 >{{item.uniqueCodeList[0].goodsCode}}
						 <text class="icon-sj red iconfont iconxiasanjiaoxing"></text>
						 </text>
					</view>
					<view class="tui-goods-sub">
						状态：
						<text class="status">{{getGoodsStatus(item.detGoodsStatus)}}</text>
					</view>
					<view class="tui-price-box">
						<view class="tui-goods-price">￥{{item.goodsPrice}}</view>
						<view class="tui-goods-num">x{{item.uniqueCodeList.length}}</view>
					</view>
				</view>
			</view>
			<view class="order-price">
				<view>总金额：<text class="red">￥{{detail.orderInfo.realAmount}}</text><text v-if="returnPrice>0">（已退：￥{{returnPrice}}）</text></view>
				<view>总数量：<text class="red">{{totalNum}}</text><text v-if="returnPrice>0">（已退：{{returnNum}}）</text></view>
			</view>
		</view>
		<view class="order-section pd2">
			<template v-if="isMember==='notgk'">
				<view class="user-item">
					<view class="left">顾客姓名</view>
					<view class="right">{{detail.customers.userName?detail.customers.userName:detail.customers.nickName}}</view>
				</view>
				<view class="user-item">
					<view class="left">手机号</view>
					<view class="right">{{detail.customers.userMobile?detail.customers.userMobile:'暂无'}}</view>
				</view>
				<view class="user-item">
					<view class="left">销售人员</view>
					<view class="right">{{detail.orderInfo.salemanName?detail.orderInfo.salemanName:'暂无'}}<text v-if="detail.orderInfo.salemanId">({{detail.orderInfo.salemanId}})</text></view>
				</view>
				<view class="user-item">
					<view class="left">所属经销商</view>
					<view class="right">{{detail.orderInfo.dealerName?detail.orderInfo.dealerName:'暂无'}}<text v-if="detail.orderInfo.dealerId">({{detail.orderInfo.dealerId}})</text></view>
				</view>
			</template>

			<!-- 顾客 -->
			<template v-if="isMember==='gk'">
				<view class="user-item">
					<view class="left">经销商会员码</view>
					<view class="right">{{detail.orderInfo.dealerId?detail.orderInfo.dealerId:'暂无'}}</view>
				</view>
				<view class="user-item">
					<view class="left">经销商姓名</view>
					<view class="right">{{detail.orderInfo.dealerName?detail.orderInfo.dealerName:'暂无'}}</view>
				</view>
			</template>
		</view>
		<view class="order-section pd3">
			<uni-steps :options="orderTime" direction="column" :active="stepsActive"></uni-steps>
		</view>
		
		<view class="order-foot-btns"
		v-if="(type==2||type==3)&&detail.productInfo.length!==detail.refundInfo.length">
			<tui-button class="btn" type="danger" width="200rpx" height="70rpx" :size="28" shape="circle" 
			@tap="scan">扫码{{type==2?'退货':'换货'}}</tui-button>
			<template v-if="returnFlag">
				<template v-if="type==2">
					<tui-button class="btn" type="danger" width="200rpx" height="70rpx" :size="28" shape="circle" @tap="sureReturn">确定</tui-button>
					<tui-button class="btn" type="black" :plain="true" width="200rpx" height="70rpx" :size="28" shape="circle" @tap="cancelReturn">取消</tui-button>
				</template>
				<template v-if="type==3">
					<tui-button class="btn" type="danger" width="200rpx" height="70rpx" :size="28" shape="circle" @tap="sureReturn">确定</tui-button>
					<tui-button class="btn" type="black" :plain="true" width="200rpx" height="70rpx" :size="28" shape="circle" @tap="cancelReturn">取消</tui-button>
				</template>
			</template>
		</view>
		<tui-modal :show="modalShow" @click="handleClick" @cancel="hide" :title="modalContent"></tui-modal>
		<!-- 商品唯一码列表 -->
		<view class="code-mask" v-if="codeFlag" @tap="hideCodesModal"></view>
		<view class="code-list" :style="{top:codeModalTop,bottom:codeModalBottom}" v-if="codeFlag">
			<!-- <view class="code-close iconfont iconguanbi3"></view> -->
			<view class="code-list-title">
				<view class="code">产品码</view>
				<view class="status">状态</view>
			</view>
			<view class="code-list-con">
				<view class="code-list-item" v-for="item in codeList">
					<view class="code">{{item.goodsCode}}</view>
					<view class="status">{{getGoodsStatus(item.detGoodsStatus)}}</view>
				</view>
			</view>
		</view>


		<!-- 扫码功能 -->
		<!-- 兼容微信小程序 -->
		<!-- #ifdef MP-WEIXIN -->
		<view class="scan-wrap" v-if="scanFlag">
			<camera-scan :scanTip="scanTip" @close="closeCashScan" @scanCode="cashScanCode"></camera-scan>
		</view>
		<!-- #endif -->
	</view>
</template>

<script>
	// #ifdef MP-WEIXIN
	import cameraScan from "@/packageC/components/camera/camera.vue"
	// #endif
	import uniCopy from '@/utils/uni-copy.js'
	import uniSteps from "@/components/uni-steps/uni-steps.vue"
	import tuiButton from '@/components/button/button';
	export default {
		components: {
			// #ifdef MP-WEIXIN
			cameraScan,
			// #endif
			uniSteps,
			tuiButton,
		},
		props: {
			tempCode: {
				type: String,
				default: '',
			},
			// totalAmount: {
			// 	type: String,
			// 	default: '',
			// },
			type: {
				type: Number,
				default: 1, //详情为1，退货2，换货3
			},
			orderId: {
				type: String,
				default: '',
			},
			version: {
				type: String,
				default: '',
			},

		},
		data() {
			return {
				imgSrc: this.$store.state.imgUrl,
				detail: null,
				orderTime: [],
				stepsActive:0,
				codeFlag: false, //显示产品码
				codeList: [], //当前产品码列表,
				afterList: [], //转换后的商品list
				totalPrice: 0, //总金额
				totalNum:0,//商品总数量
				returnPrice: 0, //退货总金额
				returnNum:0,//退货商品总数量
				
				orderCode: this.tempCode,
				scanFlag: false,
				scanTip: '',
				goodsUniqueCode: '',
				oldGoodsUniqueCode: '',
				returnFlag: false,
				modalShow: false,
				modalContent: '',
				isMember: '',
				codeModalTop:'0rpx',
				codeModalBottom:'0rpx',
				windowHeight:0,
				orgLv:'',
				returnCurGoods:{},//当前退款的商品
			}
		},
		created() {
			let that=this;
			if (uni.getStorageSync('orgLv') !== 'gk') { //不用true,false,防止界面闪现
				this.isMember = 'notgk'
			} else {
				this.isMember = 'gk'
			}
			if(this.orderCode){
				this.storeOrderDetail();
			}
			//获取屏幕高度
			uni.getSystemInfo({
				success: function (res) {
					that.windowHeight=res.windowHeight;
				}
			})
			
			if(uni.getStorageSync('storeOrgLv')){
				this.orgLv=uni.getStorageSync('storeOrgLv')
			}else{
				this.orgLv=uni.getStorageSync('orgLv')
			}
		},
		watch: {
			tempCode(val) {
				this.orderCode = val;
				this.storeOrderDetail()
			}
		},
		mounted() {
			// #ifdef APP-PLUS
			this.$eventHub.$off('appScanCode');
			this.$eventHub.$on('appScanCode',(codeRes) => {
				this.cashScanCode(codeRes)
			});
			// #endif
		},
		methods: {
			getGoodsStatus(status) {
				return ["待支付", "已支付", "已取消", "已退货", "已换货", "退货中", "已完成"][status - 1]
			},
			getOrderStatus(status) {
				return ["订单生成", "待支付", "已支付", "已取消", "已完成", "已退换"][status - 1]
			},
			storeOrderDetail() { //商品详情获取
			let that=this;
				this.$http.storeOrderDetail(this.orderCode).then((res) => {
					if (res.status === 0) {
						this.detail = res.data;
						if(!this.detail.refundInfo){
							this.detail.refundInfo=[];
						}
						if(!this.detail.orderChangeInfo){
							this.detail.orderChangeInfo=[];
						}
						let productInfo = res.data.productInfo; //以商品唯一码为维度，需要将商品码一致，并且状态一致的合并
						let orderChangeInfo = res.data.orderChangeInfo;
						let refundInfo = res.data.refundInfo;
						let tempArr = []; //记录所有的goodsId
						let afterData = [];
						this.totalPrice = 0;

						let goodsImgArr=res.data.goodsImgsInfo;
						

						productInfo.forEach(item => {
							for(let i=0;i<goodsImgArr.length;i++){
								if(goodsImgArr[i].goodsId===item.goodsId){
									item.imgUrl=goodsImgArr[i].imgReuri
									break;
								}
							}
							
							
							this.totalPrice += item.goodsPrice;
							this.totalNum+=1;
							if(item.detGoodsStatus===4){//已退货
								this.returnPrice+= item.goodsPrice;
								this.returnNum+=1;
							}
							let uniqueCode=item.goodsId+item.goodsMatcode+item.detGoodsStatus
							if (tempArr.indexOf(uniqueCode) === -1) {
								item.uniqueCodeList=[{
											goodsUniqueCode: item.goodsUniqueCode,
											goodsCode: item.goodsCode,
											detGoodsStatus: item.detGoodsStatus,
										}];
									afterData.push(item)	
								tempArr.push(uniqueCode);
							} else {
								for (let j = 0; j < afterData.length; j++) {
									if (afterData[j].goodsId == item.goodsId && afterData[j].goodsMatcode == item.goodsMatcode && afterData[j].detGoodsStatus == item.detGoodsStatus ) {
										afterData[j].uniqueCodeList.push({
											goodsUniqueCode: item.goodsUniqueCode,
											goodsCode: item.goodsCode,
											detGoodsStatus: item.detGoodsStatus,
										});
										break;
									}
								}
							}
						})
						
						this.afterList = afterData;
						console.log(this.afterList)
						console.log(9999999999)
						//订单生成1，待支付2，
						this.orderTime = [{
								title: '订单创建时间',
								desc: this.detail.orderInfo.createTime
							}
						];
						if(this.detail.orderInfo.orderStatus==1||this.detail.orderInfo.orderStatus==2){
							this.stepsActive=0
						}else if(this.detail.orderInfo.orderStatus==4){
							//已取消4
							this.orderTime.push({
									title: '订单取消时间',
									desc: this.detail.orderInfo.updateTime
								})
						}else{
							this.orderTime.push({
								title: '订单付款时间',
								desc: this.detail.orderInfo.payTime
							})
							
								
						}
						
						let refundTime=''
						let orderChangeTime=''
						
						// refundInfo
						// orderChangeInfo
						if(!refundInfo){
							refundInfo=[]
						}
						if(!orderChangeInfo){
							orderChangeInfo=[]
						}
						let newRefundAndChange=[...refundInfo,...orderChangeInfo]
						newRefundAndChange.sort(function(a, b) {
							return that.dateToTime(a.createTime)> that.dateToTime(b.createTime) ? 1 : -1;//顺序
						});
						newRefundAndChange.forEach(item=>{
							if(item.detGoodsStatus==4){//退货
								this.orderTime.push({
									title: '订单退货时间',
									desc: item.createTime
								})
							}else{
								this.orderTime.push({
									title: '订单换货时间',
									desc: item.createTime
								})
							}
						})					
					
						if(this.detail.orderInfo.orderStatus==5){
							this.orderTime.push({
								title: '订单完成时间',
								desc: this.detail.orderInfo.orderFinishTime
							})	
						}
						this.stepsActive=this.orderTime.length-1;
						
				
					}
				})
			},
			dateToTime(str){
				return new Date(str).getTime(); 
			},
			copy(content) {
				uniCopy({
					content: content,
					success: (res) => {
						uni.showToast({
							title: res,
							icon: 'none'
						})
					},
					error: (e) => {
						uni.showToast({
							title: e,
							icon: 'none',
							duration: 3000,
						})
					}
				})
			},
			viewCodesModal(e,index,list) {
				console.log(e.target.y);
				console.log(this.windowHeight)
				if(this.windowHeight>(e.target.y+300)){
					this.codeModalTop=e.target.y+20+'px'
					this.codeModalBottom='auto';
					
				}else{
					this.codeModalTop='auto';
					this.codeModalBottom=this.windowHeight-(e.target.y-20)+'px';
				}
				
				this.codeFlag = true
				this.codeList = list;
			},
			hideCodesModal() {
				this.codeFlag = false
			},
			cancelReturn(){
				uni.redirectTo({
					url: '/packageC/pages/storeOrder/storeOrder'
				});
			},
			sureReturn() { //确定退货或换货
				this.modalShow = true;
				if(this.type===2){
					this.modalContent="确定退货吗？"
				}else if(this.type===3){
					this.modalContent="确定换货吗？"
				}
			},
			scan() { //扫码退货换货
				// #ifdef MP-WEIXIN
				this.scanFlag = true;
				// #endif
				// #ifdef APP-PLUS
				uni.navigateTo({
					url:'/packageC/pages/scan/scan'
				})
				// #endif
				// #ifdef H5
				this.$wechat.scanQRCode((str) => {
				     //str为扫码结果
					 this.cashScanCode(str)
				    });
				// #endif
			},
			cashScanCode(codeRes) { //扫码结果
				let that = this;
				that.scanTip = '请扫描商品二维码';
				uni.showToast({
					icon: 'none',
					title: '请扫描商品二维码',
					duration: 1000,
				})
				if (codeRes.indexOf("=") > -1) {
					let goodsUniqueCode = codeRes.split("=")[1]; //商品唯一码
					if (goodsUniqueCode.length !== 29) {
						that.scanTip = '请扫描正确的商品二维码';
						uni.showToast({
							icon: 'none',
							title: '请扫描正确的商品二维码',
							duration: 2000,
						})
						// #ifdef H5
						setTimeout(() => {
							that.$wechat.scanQRCode((str) => {
							 that.cashScanCode(str)
							});
						}, 1000);
						// #endif
						return;
					}
					if (this.type == 2) {
						let flag = false; //判断扫的旧商品是否在订单中存在
						for (let i = 0; i < this.afterList.length; i++) {
							let arr = this.afterList[i].uniqueCodeList;
							for (let j = 0; j < arr.length; j++) {
								if (arr[j].goodsUniqueCode === goodsUniqueCode) {
									that.returnCurGoods=this.afterList[i]
									flag = true;
									break;
								}
							}
						}

						if (!flag) { //不存在提示
							uni.showToast({
								icon: 'none',
								title: '此订单无该商品，请重扫',
								duration: 1000
							})
							// #ifdef H5
							setTimeout(() => {
								that.$wechat.scanQRCode((str) => {
								 that.cashScanCode(str)
								});
							}, 1000);
							// #endif
							
							return;
						} else {
							uni.showToast({
								icon: 'none',
								title: '扫描退款商品成功',
								duration: 1000,
							});
							this.goodsUniqueCode = goodsUniqueCode;
							this.returnFlag = true;
							this.closeCashScan();
						}
					} else if (this.type == 3) {
						
						console.log(11111)
						if (goodsUniqueCode.length !== 29) {
							let title = "";
							if (!this.oldGoodsUniqueCode) {
								this.scanTip = '请扫描待换货商品二维码';
								title = '请扫描待换货商品二维码';
							} else {
								title = '请扫描新商品二维码';
								this.scanTip = '请扫描新商品二维码';
							}
							uni.showToast({
								icon: 'none',
								title: title,
								duration: 1000,
							})
							// #ifdef H5
							setTimeout(() => {
								that.$wechat.scanQRCode((str) => {
								 that.cashScanCode(str)
								});
							}, 1000);
							// #endif
							return;
						}
						
						if (!this.oldGoodsUniqueCode) {
							let flag = false; //判断扫的旧商品是否在订单中存在

							for (let i = 0; i < this.afterList.length; i++) {
								let arr = this.afterList[i].uniqueCodeList;
					
								for (let j = 0; j < arr.length; j++) {
									if (arr[j].goodsUniqueCode === goodsUniqueCode) {
										flag = true;
										break;
									}
								}
							}
							console.log(22222222222222)
							console.log(flag)
							if (!flag) { //不存在提示
								uni.showToast({
									icon: 'none',
									title: '此订单无该商品，请重扫',
									duration: 1000
								})
								// #ifdef H5
								setTimeout(() => {
									that.$wechat.scanQRCode((str) => {
									 that.cashScanCode(str)
									});
								}, 1000);
								// #endif
								return;
							} else {
								uni.showToast({
									icon: 'none',
									title: '扫描旧商品成功，请扫描新商品',
									duration: 1000
								})
								this.oldGoodsUniqueCode =goodsUniqueCode
								this.scanTip = '请扫描新商品二维码'
								
								console.log(333333333333332)
								// #ifdef H5
								setTimeout(() => {
									that.$wechat.scanQRCode((str) => {
									 that.cashScanCode(str)
									});
								}, 1000);
								// #endif
							}
							
						} else {
							if (this.oldGoodsUniqueCode ===goodsUniqueCode) {
								uni.showToast({
									icon: 'none',
									title: '相同商品不能更换,请重扫',
									duration: 1000
								})
								// #ifdef H5
								setTimeout(() => {
									that.$wechat.scanQRCode((str) => {
									 that.cashScanCode(str)
									});
								}, 1000);
								// #endif
								return;
							}
							let params = {
								goodsUniqueCode: goodsUniqueCode,
								customerUserId: that.detail.orderInfo.customerUserId,
								orgLv:this.orgLv,
								loginId:uni.getStorageSync('agencyId'),
								loginName:uni.getStorageSync('storeOrgName'),
							}
							that.$http.storeCart(params).then((res) => {
								if (res.status === 0) {
									this.newGoodsUniqueCode = goodsUniqueCode
									uni.showToast({
										icon: 'none',
										title: '扫描新商品成功',
										duration: 1000,
									})
									this.returnFlag = true;
									this.closeCashScan();
								}else{
									this.closeCashScan();
									uni.redirectTo({
										url:'/packageC/pages/storeOrder/storeOrder'
									})
								}
							}).catch(()=>{
								this.closeCashScan();
								uni.redirectTo({
									url:'/packageC/pages/storeOrder/storeOrder'
								})
							})
							
						}
					}

				}else{
					that.scanTip = '请扫描正确的商品二维码';
					uni.showToast({
						icon: 'none',
						title: '请扫描正确的商品二维码',
						duration: 1500,
					})
					// #ifdef H5
					setTimeout(() => {
						that.$wechat.scanQRCode((str) => {
						 that.cashScanCode(str)
						});
					}, 1000);
					// #endif
				}

			},
			closeCashScan() {
				setTimeout(()=>{
					this.scanFlag = false
					// #ifdef APP-PLUS
					this.$eventHub.$emit('appScanClose');
					// #endif
				},1000)
			},

			handleClick(e) {
				let that = this;
				let index = e.index;
				if (index === 1) {
					if (this.type === 2) {//退货
						let params = {
							orderId: that.orderId,
							goodsUniqueCode: that.goodsUniqueCode,
							version: that.version,
						}
						this.$http.refundGoodsOfOrder(params).then((res) => {
							if (res.status === 0) {
								uni.redirectTo({
									// url: `/packageC/pages/storeCart/returnResult?orderId=${res.data.orderId}&realAmount=${res.data.realAmount}`
									url: `/packageC/pages/storeOrder/returnResult?orderCode=${this.orderCode}`

								});
							}
							// else{
							// 	this.returnFlag = false;
							// }
						})

					} else if (this.type === 3) {//换货
						let params = {
							orderId: this.orderId,
							oldGoodsUniqueCode: this.oldGoodsUniqueCode,
							newGoodsUniqueCode: this.newGoodsUniqueCode,
							version: this.version,
						}
						console.log(params);

						this.$http.exchangeGoodsOfOrder(params).then((res) => {
							if (res.status === 0) {
								uni.redirectTo({
									url: `/packageC/pages/storeOrder/exchangeResult?orderCode=${this.orderCode}`
								});
							}
							// else{
							// 	this.returnFlag = false;
							// }
						})
					}


				}
				this.hide();
			},
			hide() {
				this.modalShow = false;
			},
		}
	}
</script>

<style lang="scss">
	@import "@/packageC/static/style/common.scss";

	.com-top {
		flex-direction: row-reverse;
	}
</style>
